import { useState } from "react";
import { Container, Row, Col } from "react-bootstrap";
import contactImg from "../assets/img/contact-img.svg";
// 导入 animate css 和可见性
import 'animate.css';
import TrackVisibility from 'react-on-screen';

export const Concat = () => {
    // 表单信息 初始化
    const fromInitialDetails = {
        firstName: '',
        lastName: '',
        email: '',
        phone: '',
        message: ''
    }
    // hook 管理
    const [formDetails, setFormDetails] = useState(fromInitialDetails);
    // 提交按钮设置
    const [buttonText, setButtonText] = useState('Send');
    // api调用状态
    const [status, setStatus] = useState({});

    // 输入框变化的函数
    const onFormUpdate = (category, value) => {
        setFormDetails({
            // 拷贝表单，更新传进来的新值
            ...formDetails,
            [category]: value
        })
    }

    // 创建函数一个常量提交
    const handleSubmit = async (e) => {
        // 先阻止默认事件执行，避免
        e.preventDefault();
        // 改变按钮里面的值 正在发送中
        setButtonText("Sending...");
        // fetch 就是原生js的ajax请求
        let response = await fetch("http://localhost:5000/contact", {
            method: "POST",
            headers: {
                "Content-Type": "application/json;charset=utf-8",
            },
            // 使用json格式传输
            body: JSON.stringify(formDetails)
        });
        // 提交完后回滚到初始文本 发送
        setButtonText('Send');
        // 返回的结果解析 json
        let result = await response.json();
        // 改变表单里数据
        setFormDetails(fromInitialDetails);
        if (result.code == 200) {
            // 消息发送成功
            setStatus({ succes: true, message: 'Message sent successfully' })
        } else {
            // 出现问题，请稍后再试
            setStatus({ succes: false, message: 'Something went wrong, please try again later.' });
        }

    }

    return (
        <section className="contact" id="connect">
            <Container>
                <Row className="align-items-center">
                    <Col size={12} md={6}>
                    <TrackVisibility>
              {({ isVisible }) =>
                <img className={isVisible ? "animate__animated animate__zoomIn animate__repeat-1 " : ""} src={contactImg} alt="Contact Us"/>
              }
            </TrackVisibility>
                    </Col>
                    <Col size={12} md={6}>
                        <h2>Get In Touch 获取联系</h2>
                        {/* 表单的提交设置 */}
                        <form onSubmit={handleSubmit}>
                            <Row>
                                <Col size={12} sm={6} className="px-1">
                                    <input type="text" value={formDetails.firstName} placeholder="First Name" onChange={(e) => onFormUpdate('firstName', e.target.value)}></input>
                                </Col>
                                <Col size={12} sm={6} className="px-1">
                                    <input type="text" value={formDetails.lastName} placeholder="Last Name" onChange={(e) => onFormUpdate('lastName', e.target.value)}></input>
                                </Col>
                                <Col size={12} sm={6} className="px-1">
                                    <input type="email" value={formDetails.email} placeholder="Email Address" onChange={(e) => onFormUpdate('email', e.target.value)} />
                                </Col>
                                <Col size={12} sm={6} className="px-1">
                                    <input type="tel" value={formDetails.phone} placeholder="Phone No." onChange={(e) => onFormUpdate('phone', e.target.value)} />
                                </Col>
                                <Col size={12} className="px-1">
                                    <textarea row="6" value={formDetails.message} placeholder="Message" onChange={(e) => onFormUpdate('message', e.target.value)}>
                                    </textarea>
                                    <button type="submit"><span>{buttonText}</span></button>
                                </Col>
                                {
                                    // 发送后 收到错误或成功就显示出来
                                    status.message &&
                                    <Col>
                                        <p className={status.success === false ? "danger" : "success"}>
                                            {status.message}
                                        </p>
                                    </Col>
                                }
                            </Row>
                        </form>
                    </Col>
                </Row>
            </Container>
        </section>
    )
}